package com.iamback.dy.examine.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.iamback.dy.entity.Resource;
import com.iamback.dy.entity.ResourceRole;
import com.iamback.dy.entity.Role;
import com.iamback.dy.entity.User;
import com.iamback.dy.examine.common.Page;
import com.iamback.dy.examine.common.utils.StringUtils;
import com.iamback.dy.examine.service.IRoleService;
import com.iamback.dy.mapper.ResourceMapper;
import com.iamback.dy.mapper.RoleMapper;
import com.iamback.dy.mapper.UserMapper;

/**
 * <p>
 * 角色表  服务实现类
 * </p> 
 */
@Service
public class RoleServiceImpl implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public Page<Role> findRolePage(String searchText,Integer pageNum,Integer numPerPage) {
		Map<String , Object> map =new HashMap<String, Object>();
		int start = pageNum ==0?0:(pageNum-1)*numPerPage;
		map.put("name", searchText);
		map.put("pageNum", start);
		map.put("numPerPage", numPerPage);
		Page<Role> page= new Page<Role>();
		Integer count  = roleMapper.findRoleByPageCount(map);
		if(count!=null && count >0){
		    List<Role> roles = roleMapper.findRoleByPage(map);
		    page.setContent(roles);
		    page.setTotalElements(count);
		}else{
			 page.setTotalElements(0);
		}
		return page;
	}
	
	@Override
	public void saveOrUpdate(Role role) {
		if(role.getId() != null){
			Role dbRole = roleMapper.findRoleById(role.getId());
			dbRole.setUpdateTime(new Date());
			dbRole.setName(role.getName());
			dbRole.setDescription(role.getDescription());
			dbRole.setUpdateTime(new Date());
			dbRole.setStatus(role.getStatus());
			roleMapper.updateRole(dbRole);
		}else{
			role.setCreateTime(new Date());
			role.setUpdateTime(new Date());
			roleMapper.saveRole(role);
		}
	}
	
	@Override
	public Set<Role> getRoleList(Integer userId){
		List<Role> list =roleMapper.getListByUserId(userId);
		Set<Role> permsSet = new HashSet<Role>();
		for(Role perm:list){
			permsSet.addAll(Arrays.asList(perm));
		}
		return permsSet;
	}
	
	
	@Override
	public void delete(Integer id) {
		Role role = roleMapper.findRoleById(id);
		Assert.state(!"administrator".equals(role.getRoleKey()),"超级管理员角色不能删除");
		Map<String ,Object> map =new HashMap<String, Object>();
		map.put("roleId", id);
		roleMapper.deleteResourceRole(map);
		userMapper.deleteUserRole(map);
		roleMapper.deleteRole(id);
	}

	@Override
	public void grant(Integer id, String[] resourceIds) {
		Role role = roleMapper.findRoleById(id);
		Assert.notNull(role, "角色不存在");
		Assert.state(!"administrator".equals(role.getRoleKey()),"超级管理员角色不能进行资源分配");
	    List<ResourceRole>  resourceRoles =new ArrayList<ResourceRole>();
		if(resourceIds != null){
			for (int i = 0; i < resourceIds.length; i++) {
				if(StringUtils.isBlank(resourceIds[i]) || "0".equals(resourceIds[i])){
					continue;
				}
				Integer rid = Integer.parseInt(resourceIds[i]);
				Resource resource = resourceMapper.findResourceById(rid);
				ResourceRole roleResult = new ResourceRole();
				roleResult.setResourceId(resource.getId());
				roleResult.setRoleId(id);
				resourceRoles.add(roleResult);
			}
			Map<String, Object> map =new HashMap<String, Object>();
			map.put("roleId", id);
			roleMapper.deleteResourceRole(map); 
			roleMapper.saveResourceRole(resourceRoles);
		} 
	}
	
	@Override
	public Role findRoleById(Integer id){
		return roleMapper.findRoleById(id);
	}
	@Override
    public List<Role> findAll(){
    	return roleMapper.findRole(null); 		
    }


}
